package com.chenshu.shop.controller.index;

import com.chenshu.shop.common.Constant;
import com.chenshu.shop.common.SessionUtil;
import com.chenshu.shop.model.Cart;
import com.chenshu.shop.model.Good;
import com.chenshu.shop.model.User;
import com.chenshu.shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-12
 * Time：16:58
 */
@Controller
@RequestMapping("/index")
public class CartController {
    @Autowired
    private CartService cartService;

    @RequestMapping("/cart")
    public String redirectCart(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(Constant.SESSION_USER_INFO_KEY);
        List<Cart> cartList = cartService.getCartsByUid(user.getId());
        request.setAttribute("cartList", cartList);
        //计算总价
        Integer cartTotal = 0;
        for (Cart cart : cartList) {
            cartTotal += cart.getTotal();
        }
        request.setAttribute("cartTotal", cartTotal);
        return "forward:/index/cart.jsp";
    }

    @ResponseBody
    @RequestMapping( value = "/cartBuy" , produces = "text/html; charset=UTF-8")
    public String cartBuy(HttpServletRequest request, Integer goodId) {
        User user = SessionUtil.getLoginUser(request);
        assert user != null;
        boolean flag = cartService.buyCart(user.getId(), goodId);
        if (flag)
            return "成功";
        else
            return "失败";
    }

    @ResponseBody
    @RequestMapping("/cartAdd")
    public String cartAdd(Integer id) {
        cartService.addCart(id);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/cartLess")
    public String cartLess(Integer id) {
        cartService.decreaseCart(id);
        return "ok";
    }

    @RequestMapping("/cartDelete")
    public String cartDelete(Integer id) {
        cartService.deleteCart(id);
        return "redirect:/index/cart";
    }

    @ResponseBody
    @RequestMapping("/cartCount")
    public Integer cartCount(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            return (Integer) session.getAttribute(Constant.USER_CART_COUNT);
        }
        return null;
    }
}
